<template>
  <div class="register-container">
    <div class="register-content">
      <h1 class="title">教师账号注册</h1>
      
      <div class="register-form">
        <div class="form-item">
          <label>工号：</label>
          <input 
            v-model="registerForm.employee_id" 
            type="text" 
            class="form-input"
            placeholder="请输入工号"
            @blur="checkEmployeeId"
          />
        </div>

        <div class="form-item">
          <label>密码：</label>
          <input 
            v-model="registerForm.password" 
            type="password" 
            class="form-input"
            placeholder="请输入密码"
          />
        </div>

        <div class="form-item">
          <label>确认密码：</label>
          <input 
            v-model="registerForm.confirmPassword" 
            type="password" 
            class="form-input"
            placeholder="请再次输入密码"
          />
        </div>

        <div class="form-item">
          <label>姓名：</label>
          <input 
            v-model="registerForm.real_name" 
            type="text" 
            class="form-input"
            placeholder="请输入真实姓名"
          />
        </div>

        <div class="form-item">
          <label>手机：</label>
          <input 
            v-model="registerForm.phone" 
            type="tel" 
            class="form-input"
            placeholder="请输入手机号"
            @blur="checkPhone"
          />
        </div>

        <div class="form-item">
          <label>邮箱：</label>
          <input 
            v-model="registerForm.email" 
            type="email" 
            class="form-input"
            placeholder="请输入邮箱地址"
            @blur="checkEmail"
          />
        </div>

        <div class="form-item">
          <label>职位：</label>
          <input 
            v-model="registerForm.professional_title" 
            type="text" 
            class="form-input"
            placeholder="请输入专业职位"
          />
        </div>

        <div class="form-item">
          <label>身份证号：</label>
          <input 
            v-model="registerForm.id_card" 
            type="text" 
            class="form-input"
            placeholder="请输入身份证号"
            maxlength="18"
            @blur="checkIdCard"
          />
        </div>
        
        <div class="button-group">
          <button class="back-btn" @click="handleBack">返回登录</button>
          <button class="register-btn" @click="handleRegister">提交注册</button>
        </div>
      </div>
    </div>

    <!-- 自定义弹窗 -->
    <div v-if="showModal" class="modal-overlay" @click="closeModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>{{ modalTitle }}</h3>
          <button class="close-btn" @click="closeModal">×</button>
        </div>
        <div class="modal-body">
          <div class="icon-wrapper">
            <div class="info-icon" :class="modalType">
              {{ modalType === 'success' ? '✓' : '!' }}
            </div>
          </div>
          <p class="modal-text">{{ modalText }}</p>
          <p v-if="modalContactInfo" class="contact-info">{{ modalContactInfo }}</p>
        </div>
        <div class="modal-footer">
          <button class="confirm-btn" @click="closeModal">我知道了</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useTokenStore } from '@/stores/token.js'
import { teacherRegisterService, checkEmployeeIdService, checkIdCardService, checkPhoneService, checkEmailService } from '@/api/teacher.js'

const router = useRouter()
const tokenStore = useTokenStore()

// 表单数据
const registerForm = reactive({
  employee_id: '',
  password: '',
  confirmPassword: '',
  real_name: '',
  phone: '',
  email: '',
  professional_title: '',
  id_card: ''
})

// 弹窗控制
const showModal = ref(false)
const modalTitle = ref('')
const modalText = ref('')
const modalContactInfo = ref('')
const modalType = ref('info')

// 显示弹窗
const showCustomModal = (title, text, type = 'info', contactInfo = '') => {
  modalTitle.value = title
  modalText.value = text
  modalType.value = type
  modalContactInfo.value = contactInfo
  showModal.value = true
}

// 检查工号是否存在
const checkEmployeeId = async () => {
  if (!registerForm.employee_id) {
    return
  }
  
  try {
    const response = await checkEmployeeIdService(registerForm.employee_id)
    if (response.code === 200 && response.data === true) {
      showCustomModal('提示', '该工号已存在，请使用其他工号')
    }
  } catch (error) {
    // 静默处理检查错误，不影响用户体验
    console.error('检查工号失败:', error)
  }
}

// 检查身份证号是否存在
const checkIdCard = async () => {
  if (!registerForm.id_card) {
    return
  }
  
  // 先验证身份证号格式
  const idCardReg = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
  if (!idCardReg.test(registerForm.id_card)) {
    return // 格式不正确时不检查重复
  }
  
  try {
    const response = await checkIdCardService(registerForm.id_card)
    if (response.code === 200 && response.data === true) {
      showCustomModal('提示', '该身份证号已被注册，请检查身份证号是否正确')
    }
  } catch (error) {
    console.error('检查身份证号失败:', error)
  }
}

// 检查手机号是否存在
const checkPhone = async () => {
  if (!registerForm.phone) {
    return
  }
  
  // 先验证手机号格式
  const phoneReg = /^1[3-9]\d{9}$/
  if (!phoneReg.test(registerForm.phone)) {
    return // 格式不正确时不检查重复
  }
  
  try {
    const response = await checkPhoneService(registerForm.phone)
    if (response.code === 200 && response.data === true) {
      showCustomModal('提示', '该手机号已被注册，请使用其他手机号')
    }
  } catch (error) {
    console.error('检查手机号失败:', error)
  }
}

// 检查邮箱是否存在
const checkEmail = async () => {
  if (!registerForm.email) {
    return
  }
  
  // 先验证邮箱格式
  const emailReg = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!emailReg.test(registerForm.email)) {
    return // 格式不正确时不检查重复
  }
  
  try {
    const response = await checkEmailService(registerForm.email)
    if (response.code === 200 && response.data === true) {
      showCustomModal('提示', '该邮箱已被注册，请使用其他邮箱')
    }
  } catch (error) {
    console.error('检查邮箱失败:', error)
  }
}

// 表单验证
const validateForm = async () => {
  if (!registerForm.employee_id) {
    showCustomModal('提示', '请输入工号')
    return false
  }
  
  // 提交前再次检查各字段是否存在
  try {
    // 检查工号
    const employeeIdResponse = await checkEmployeeIdService(registerForm.employee_id)
    if (employeeIdResponse.code === 200 && employeeIdResponse.data === true) {
      showCustomModal('提示', '该工号已存在，请使用其他工号')
      return false
    }
    
    // 检查身份证号
    const idCardResponse = await checkIdCardService(registerForm.id_card)
    if (idCardResponse.code === 200 && idCardResponse.data === true) {
      showCustomModal('提示', '该身份证号已被注册，请检查身份证号是否正确')
      return false
    }
    
    // 检查手机号
    const phoneResponse = await checkPhoneService(registerForm.phone)
    if (phoneResponse.code === 200 && phoneResponse.data === true) {
      showCustomModal('提示', '该手机号已被注册，请使用其他手机号')
      return false
    }
    
    // 检查邮箱
    const emailResponse = await checkEmailService(registerForm.email)
    if (emailResponse.code === 200 && emailResponse.data === true) {
      showCustomModal('提示', '该邮箱已被注册，请使用其他邮箱')
      return false
    }
  } catch (error) {
    console.error('字段重复检查失败:', error)
    // 检查失败时继续流程，避免影响正常注册
  }
  
  if (!registerForm.password || registerForm.password.length < 6) {
    showCustomModal('提示', '密码不能少于6位')
    return false
  }
  
  if (!registerForm.confirmPassword) {
    showCustomModal('提示', '请输入确认密码')
    return false
  }
  
  if (registerForm.password !== registerForm.confirmPassword) {
    showCustomModal('提示', '两次输入的密码不一致')
    return false
  }
  
  if (!registerForm.real_name) {
    showCustomModal('提示', '请输入真实姓名')
    return false
  }
  
  // 手机号验证
  const phoneReg = /^1[3-9]\d{9}$/
  if (!registerForm.phone) {
    showCustomModal('提示', '请输入手机号')
    return false
  } else if (!phoneReg.test(registerForm.phone)) {
    showCustomModal('提示', '请输入正确的手机号格式')
    return false
  }
  
  // 邮箱验证
  const emailReg = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!registerForm.email) {
    showCustomModal('提示', '请输入邮箱地址')
    return false
  } else if (!emailReg.test(registerForm.email)) {
    showCustomModal('提示', '请输入正确的邮箱格式')
    return false
  }
  
  if (!registerForm.professional_title) {
    showCustomModal('提示', '请输入专业职位')
    return false
  }
  
  // 身份证验证
  const idCardReg = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
  if (!registerForm.id_card) {
    showCustomModal('提示', '请输入身份证号')
    return false
  } else if (!idCardReg.test(registerForm.id_card)) {
    showCustomModal('提示', '请输入正确的身份证号格式')
    return false
  }
  
  return true
}

// 注册处理
const handleRegister = async () => {
  if (!(await validateForm())) {
    return
  }
  
  try {
    // 调用注册API
    console.log('提交注册信息:', registerForm)
  
    const response = await teacherRegisterService(registerForm)
    
    // 注册成功
    if (response.code === 200) {
      showCustomModal(
        '注册申请已提交', 
        '您的注册申请已成功提交！请等待管理员审核通过后再进行登录。审核通过前暂时无法登录系统。', 
        'success'
      )
    } else {
      showCustomModal('注册失败', response.message || '注册失败，请稍后重试')
    }
  } catch (error) {
    console.error('注册失败:', error)
    // 处理错误响应
    let errorMessage = error.msg || error.message || '注册过程中发生错误，请稍后重试'
    
    // 特殊错误处理
    if (errorMessage.includes('Duplicate entry') && errorMessage.includes('uk_id_card')) {
      errorMessage = '该身份证号已被注册，请检查身份证号是否正确'
    } else if (errorMessage.includes('Duplicate entry') && errorMessage.includes('uk_employee_id')) {
      errorMessage = '该工号已存在，请使用其他工号'
    } else if (errorMessage.includes('Duplicate entry') && errorMessage.includes('phone')) {
      errorMessage = '该手机号已被注册，请使用其他手机号'
    } else if (errorMessage.includes('Duplicate entry') && errorMessage.includes('email')) {
      errorMessage = '该邮箱已被注册，请使用其他邮箱'
    }
    
    showCustomModal('注册失败', errorMessage)
  }
}

// 返回登录
const handleBack = () => {
  router.push('/login')
}

// 关闭弹窗
const closeModal = () => {
  showModal.value = false
  // 如果是成功注册，关闭弹窗后跳转到登录页
  if (modalType.value === 'success') {
    setTimeout(() => {
      // 清除可能存在的token，确保可以跳转到登录页
      tokenStore.removeToken()
      router.push('/login')
    }, 500)
  }
}
</script>

<style scoped lang="scss">
@import '@/assets/css/register.css';
</style> 